package com.hgsoft.pubsv.component.apifilter.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

import org.apache.tomcat.util.codec.binary.Base64;

import com.hgsoft.pubsv.component.base.Constants;
import com.hgsoft.pubsv.component.base.execption.ApiCodeException;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description: AES 加解密工具类
 *
 */
@Slf4j
public class AESUtil {

	private static final String ALGORITHM = "AES";
	private static final String CHARSET_UTF8="UTF-8";
	private static final int KEY_SIZE = 128;
	private static final int CACHE_SIZE = 1024;
	
	//参数分别代表 算法名称/加密模式/数据填充方式
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    /**
     * 加密
     * @param content 加密的字符串
     * @param encryptKey key值(16位字符串)
     * @return
     * @throws Exception
     */
    public static String encrypt(String content, String encryptKey,String charset) throws Exception {
        try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128);
			Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
			cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(charset), "AES"));
			byte[] b = cipher.doFinal(content.getBytes(charset));
			// 采用base64算法进行转码,避免出现中文乱码
			return Base64.encodeBase64String(b);
		} catch (Exception e) {
			log.error("encrypt content:{},e:{}",content,e);
			throw new ApiCodeException(Constants.ERR_ENCRYPTION_FAILED,Constants.ERR_ENCRYPTION_FAILED_NAME);
		}
 
    }
 
    /**
     * 解密
     * @param encryptStr 解密的字符串(16位字符串)
     * @param decryptKey 解密的key值
     * @param charset 字符编码
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptStr, String decryptKey,String charset) throws Exception {
        try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128);
			Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
			cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(charset), "AES"));
			// 采用base64算法进行转码,避免出现中文乱码
			byte[] encryptBytes = Base64.decodeBase64(encryptStr);
			byte[] decryptBytes = cipher.doFinal(encryptBytes);
			return new String(decryptBytes);
		} catch (Exception e) {
			log.error("decrypt encryptStr:{},decryptKey:{},e:{}",encryptStr,decryptKey,e);
			throw new ApiCodeException(Constants.ERR_DECRYPT_FAILED,Constants.ERR_DECRYPT_FAILED_NAME);
		}
    }

	/**
	 * 加密文件
	 * 
	 * @param key             密钥(16位字符串)
	 * @param sourceFilePath  原文件路径
	 * @param encryptFilePath 加密文件路径
	 * @param charset 字符编码
	 * @throws Exception
	 */
	public static void encryptFile(String key, String sourceFilePath, String encryptFilePath) throws Exception {
		File sourceFile = new File(sourceFilePath);
		File encryptFile = new File(encryptFilePath);

		if (!sourceFile.isFile()) {
			throw new Exception(sourceFilePath + " is not a file");
		}

		if (!sourceFile.exists()) {
			throw new Exception(sourceFilePath + " not exist");
		}

		if (!encryptFile.getParentFile().exists()) {
			encryptFile.getParentFile().mkdirs();
		}

		encryptFile.createNewFile();
		InputStream inputStream = new FileInputStream(sourceFile);
		OutputStream outputStream = new FileOutputStream(encryptFile);
		Key k = new SecretKeySpec(Base64.decodeBase64(key), ALGORITHM);
		byte[] raw = k.getEncoded();
		SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
		CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
		byte[] cache = new byte[CACHE_SIZE];
		int read = 0;
		while ((read = cipherInputStream.read(cache, 0, cache.length)) != -1) {
			outputStream.write(cache, 0, read);
		}
		outputStream.close();
		cipherInputStream.close();
		inputStream.close();
	}

	/**
	 * 解密文件
	 * 
	 * @param key             密钥
	 * @param encryptFilePath 加密文件路径
	 * @param targetFilePath  目标文件路径
	 * @throws Exception
	 */
	public static void decryptFile(String key, String encryptFilePath, String targetFilePath) throws Exception {
		File encryptFile = new File(encryptFilePath);
		File targetFile = new File(targetFilePath);

		if (!encryptFile.isFile()) {
			throw new Exception(encryptFilePath + " is not a file");
		}

		if (!encryptFile.exists()) {
			throw new Exception(encryptFilePath + " not exist");
		}

		if (!targetFile.getParentFile().exists()) {
			targetFile.getParentFile().mkdirs();
		}

		targetFile.createNewFile();
		InputStream inputStream = new FileInputStream(encryptFile);
		OutputStream outputStream = new FileOutputStream(targetFile);
		Key k = new SecretKeySpec(Base64.decodeBase64(key), ALGORITHM);
		byte[] raw = k.getEncoded();
		SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
		CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
		byte[] cache = new byte[CACHE_SIZE];
		int read = 0;
		while ((read = inputStream.read(cache, 0, cache.length)) != -1) {
			cipherOutputStream.write(cache, 0, read);
		}
		outputStream.close();
		cipherOutputStream.close();
		inputStream.close();
	}
	
}
